package com.zwz.crawler.basic;
import com.zwz.constant.Constant;
import com.zwz.parse.JsonParserUtil;
import com.zwz.vo.MemInfo;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

import static com.zwz.constant.Constant.ENTERPRISE_ID;

@Slf4j
public class TungeeMemberQuery {
    // 配置参数
//    private static final String ENTERPRISE_ID = "577de19eadf21dc4";
    private static final int START = 0;
    private static final int END = 10;
    private static final int MAX_PAGE_SIZE = 50;

    public static MemInfo startTungeeMemberQuery( String  ENTERPRISE_ID) {
        // 参数校验
        validateParameters(START, END);

        try {
            // 构建精准URL
            String encodedId = URLEncoder.encode(ENTERPRISE_ID, String.valueOf(StandardCharsets.UTF_8));
            String url = String.format(
                    "https://sales.tungee.com/api/enterprise/detail/member-page?enterprise_id=%s&start=%d&end=%d",
                    encodedId, START, END
            );

            // 发送请求
            Connection.Response response = Jsoup.connect(url)
                    .method(Connection.Method.GET)
                    // 请求头精确配置
                    .header("authority", "sales.tungee.com")
                    .header("accept", "*/*")
                    .header("accept-encoding", "gzip, deflate, br, zstd")
                    .header("accept-language", "zh-CN,zh;q=0.9")
                    .header("cache-control", "no-cache")
                    .header("cookie", Constant.cookies)
                    .header("pragma", "no-cache")
                    .header("priority", "u=1, i")
                    .header("referer", "https://sales.tungee.com/enterprise-details/" + ENTERPRISE_ID + "/enterprise-information/basic-information")
                    .header("sec-ch-ua", "\"Not;A=Brand\";v=\"24\", \"Chromium\";v=\"128\"")
                    .header("sec-ch-ua-mobile", "?0")
                    .header("sec-ch-ua-platform", "\"Windows\"")
                    .header("sec-fetch-dest", "empty")
                    .header("sec-fetch-mode", "cors")
                    .header("sec-fetch-site", "same-origin")
                    .header("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36")
                    .header("x-tonxis-pid", "67864ea75f69e05d3b544ca7")
                    .header("Accept-Encoding", "gzip, deflate") // 控制压缩方式
                    // 连接配置
                    .ignoreContentType(true)
                    .ignoreHttpErrors(true)
                    .maxBodySize(0)
                    .timeout(30000)
                    .execute();

            // 处理响应
            processResponse(response);


            //解析
         return    JsonParserUtil.ParseShold(response.body());

        } catch (IOException e) {
            handleNetworkError(e);
        }
        return null;
    }

    private static String getLatestCookies() {
        return "_tx_pid=67864ea75f69e05d3b544ca7; __wpkreporterwid_=cc4a07fc-7bb9-40a4-96bc-2cbac34b658f; "
                + "__last_enter_version=sales; _co_i=6805a5576eceb9637696f09d; _tx_uid=680701dddca941522b77e864; "
                + "_tx_cid=6805a5576eceb9637696f09d; DISTINCT_ID=b84fe276-099f-4932-92b3-d54b92ae384b; "
                + "_tx_sid=MTc0NTMwMTE0MzYyMjo4MmQ2OTQ5MTY0NjU2ODNmYjQ5MjlmMjc3NDg5ZDFlZg==; "
                + "SecurityCenterDuId=ImFBSG15RzdPdVdPdCtsWnNGMFVuSXhVPSI.GuzDmQ.Pxm3uG40J8gTQGNwc2K6fX_MFS0; "
                + "remember_token=680b3219dca94151d0217627|34818d350c18319a1eeb92d5dbe213bb4b12acaa3b376797d72ad39e95e124fb0e49b10789a251113f9e7472d910d453bc4132777b1795cb3511954bea5f068a; "
                + "acw_tc=1a0c385017457190869754714e0054f533aad5ab2a40117414af54d54b8c5e; "
                + "Hm_lvt_f2ee75449fc055cc4dbceb4fe403bea3=1745562840,1745562921,1745564178,1745719089; HMACCOUNT=B4E402DF057C895E; "
                + "tg_referrer_source=https%3A%2F%2Fuser.tungee.com%2F; Hm_lpvt_f2ee75449fc055cc4dbceb4fe403bea3=1745720358; "
                + "accountCenterSessionId=.eJw9y7sKwjAUgOF3OXOHJPZiuyoFweMUkXQJSXN6o63QRIWK725xcPzh-98wEzntzZN0uGtnoWjM6CkC3Szku3_63kEBlcQEbyjwqAJO5YQHxpSs-rNsYzWcglqv7LKWvZJuQKkYRPDwtOjfnO6Z3Qmeu9rkMU-4Y4Jnqcg2VHdmnmnc0IssfL6kKi9A.Gu8lpg.-CXiJHqDsBXELVovG_KLVbswZKo; "
                + "doncusSessionId=eyJfZnJlc2giOmZhbHNlLCJ1c2VyX2lkIjoiNjgwNzAxZGRkY2E5NDE1MjJiNzdlODY0In0.Gu8lqA.Tm3eyYwnIHyWeH2Fcs9U45SMLMQ";
    }

    private static void validateParameters(int start, int end) {
        if (start < 0) throw new IllegalArgumentException("起始位置不能为负数");
        if (end <= start) throw new IllegalArgumentException("结束位置必须大于起始位置");
        if (end - start > MAX_PAGE_SIZE) throw new IllegalArgumentException("单次请求最多获取" + MAX_PAGE_SIZE + "条记录");
    }

    private static void processResponse(Connection.Response response) {
       log.info("=== 响应信息 ===");
       log.info("URL: " + response.url());
       log.info("状态码: " + response.statusCode());

        switch (response.statusCode()) {
            case 200:
               log.info("\n=== 企业成员数据 ===");
               log.info(response.body());
                break;
            case 401:
                System.err.println("[认证失效] 需要更新以下Cookie：");
                System.err.println("1. accountCenterSessionId");
                System.err.println("2. doncusSessionId");
                break;
            case 403:
                System.err.println("[权限不足] 可能原因：");
                System.err.println("1. 当前账号无成员信息查看权限");
                System.err.println("2. 企业ID " + ENTERPRISE_ID + " 不属于当前账户");
                break;
            case 429:
                System.err.println("[请求频繁] 建议：");
                System.err.println("1. 添加3-8秒随机延迟");
                System.err.println("2. 使用代理服务器轮换IP");
                break;
            default:
                System.err.println("异常响应: " + response.statusMessage());
                System.err.println("响应内容: " + response.body());
        }
    }

    private static void handleNetworkError(IOException e) {
        System.err.println("\n=== 网络错误 ===");
        if (e.getMessage().contains("Connection timed out")) {
            System.err.println("连接超时解决方案：");
            System.err.println("1. 检查网络连接状态");
            System.err.println("2. 尝试使用VPN连接");
        } else if (e.getMessage().contains("Host unresolved")) {
            System.err.println("域名解析失败：");
            System.err.println("1. 检查DNS设置（建议使用8.8.8.8）");
            System.err.println("2. 确认域名拼写正确");
        } else {
            System.err.println("未知网络异常：");
            e.printStackTrace();
        }

    }

    // 分页查询自动化示例
    public static void paginationQuery() throws IOException, InterruptedException {
        int pageSize = 10;
        for (int page = 0; ; page++) {
            int start = page * pageSize;
            int end = start + pageSize;

            String url = String.format(
                    "https://sales.tungee.com/api/enterprise/detail/member-page?enterprise_id=%s&start=%d&end=%d",
                    URLEncoder.encode(ENTERPRISE_ID, String.valueOf(StandardCharsets.UTF_8)), start, end
            );

            Connection.Response res = Jsoup.connect(url)
//                    .headers(getHeaders())
                    .execute();

            if (res.statusCode() != 200 || res.body().contains("\"total\":0")) break;

           log.info("第" + (page+1) + "页数据：");
           log.info(res.body());

            Thread.sleep(5000); // 5秒间隔
        }
    }




    //todo 需要拼起来
//    private static Connection.Headers getHeaders() {
//        return new Connection.Headers()
//                .add("authority", "sales.tungee.com")
//                .add("cookie", getLatestCookies())
//                .add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36...");
//    }

}



// 分